package com.zlyx.easy.http.dispatch;

import java.lang.reflect.Method;

import org.springframework.beans.factory.annotation.Autowired;

import com.zlyx.easy.core.exception.BusinessException;
import com.zlyx.easy.core.factory.FactoryBeanConfigurer;
import com.zlyx.easy.core.factory.defaults.annotations.FactoryBean;
import com.zlyx.easy.core.factory.interfaces.FactoryBeanDefiner;
import com.zlyx.easy.core.utils.EnvUtils;
import com.zlyx.easy.core.utils.StringUtils;
import com.zlyx.easy.http.annotations.HttpService;
import com.zlyx.easy.http.handlers.AbstractMappingHandler;
import com.zlyx.easy.http.mapping.HttpMappingConfigurer;
import com.zlyx.easy.http.models.RequestModel;
import com.zlyx.easy.http.parser.HttpMethodParser;
import com.zlyx.easy.http.parser.defaults.DefaultHttpMethodParser;

/**
 * 请求路由
 * 
 * @Auth 赵光
 * @Describle
 * @2019年12月25日
 */
@FactoryBean(annotationClass = HttpService.class, todo = "请求转发")
public class HttpMappingDispatcher implements FactoryBeanDefiner {

	@Autowired(required = false)
	private HttpMethodParser httpMethodParser;

	@Autowired(required = false)
	private HttpMappingConfigurer httpMappingConfigurer;

	@Override
	public Object excute(Class<?> proxyClass, Method method, Object[] args) throws Exception {
		RequestModel rm = httpMethodParser.parse(proxyClass, method, args);
		// 如果实现了服务映射配置接口，优先走服务映射配置;否则，走配置文件
		if (httpMappingConfigurer != null && StringUtils.isNotBlank(rm.getName())) {
			rm.setBaseUrl(StringUtils.getOrDefault(httpMappingConfigurer.getHttpUrl(rm.getName()), rm.getBaseUrl()));
		} else {
			rm.setBaseUrl(EnvUtils.getProperty(rm.getBaseUrl()));
		}
		if (rm.getUrl() == null) {
			BusinessException.throwException("请求地址不能为空!");
		}
		if (rm.getMethod() == null) {
			BusinessException.throwException("请求方式不能为空!");
		}
		return AbstractMappingHandler.call(rm);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		FactoryBeanConfigurer.addFactoryBeanHandler(this);
		if (httpMethodParser == null) {
			this.httpMethodParser = new DefaultHttpMethodParser();
		}
	}

}
